package wd

import (
	"github.com/gin-gonic/gin"
)

// Response 响应
type Response struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Debug   interface{} `json:"debug,omitempty"`
	TraceID string      `json:"trace_id,omitempty"`
}

// ResponseError 响应错误
type ResponseError struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Debug   interface{} `json:"debug,omitempty"`
	TraceID string      `json:"trace_id,omitempty"`
}

// NewResponseError 创建响应错误
func NewResponseError(code int, msg string, args ...interface{}) *ResponseError {
	var respDebug interface{}
	res := &ResponseError{
		Code: code,
		Msg:  msg,
	}
	if len(args) > 0 && App.Env == EnvDev {
		respDebug = args[0]
		res.Debug = respDebug
	}
	return res
}

// Success 成功
func Success(c *gin.Context, data interface{}) {
	c.JSON(StatusCode200, Response{
		Code:    0,
		Msg:     "success",
		Data:    data,
		TraceID: c.GetString("trace_id"),
	})
}

// Failed 失败
func Failed(c *gin.Context, err *ResponseError) {
	err.TraceID = c.GetString("trace_id")
	c.JSON(StatusCode200, err)
}

// ShowRes 显示响应
func ShowRes(c *gin.Context, res interface{}, err *ResponseError) {
	if err != nil {
		Failed(c, err)
		return
	}
	Success(c, res)
}

// CheckReq 检查请求
func CheckReq(c *gin.Context, req interface{}) *ResponseError {
	err := c.ShouldBind(req)
	if err != nil {
		return NewResponseError(StatusCode400, "请求参数错误")
	}
	return nil
}
